import {
  getSetting,
  chooseAddress,
  openSetting,
  showToast
} from '../../utils/asyncWx';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address:{},
    cartList:[],
    allChecked:false,
    totalCost:0,
    totalNum:0
  },
  //handleChooseAddress(){
    /* wx.chooseAddress({
      success: (result) => {
         
      },
      fail: () => {},
      complete: () => {}
    }); */
    //获取权限状态
    /* wx.getSetting({
      success: (result) => {
        const scopeAddress=result.authSetting["scope.address"]
        if (scopeAddress === true || scopeAddress === undefined) {
          wx.chooseAddress({
            success: (result1) => {
              console.log(result1);  
            },
          });
        }else{//用户拒绝过弹窗
          wx.openSetting({
            success: (result2) => {
              wx.chooseAddress({
                success: (result3) => {
                  console.log(result3);
                },
              });
            },
          });
            
        }
      },
    });
       
  }, */
  async handleChooseAddress(){
    try {
        //获取权限状态
      const res1 = await getSetting()
      const scopeAddress = res1.authSetting["scope.address"]
      //判断权限状态
      if (scopeAddress === true || scopeAddress === undefined){
        //调用收货地址API
        const res2=await chooseAddress()
        res2.all = res2.provinceName + res2.cityName + res2.countyName + res2.detailInfo
        wx.setStorageSync("address", res2);
        //console.log(res2);
      }else{
        //诱导用户打开授权页面
        await openSetting()
        //调用收货地址API
        const res3 = await chooseAddress()
        res3.all = res3.provinceName + res3.cityName + res3.countyName + res3.detailInfo
        wx.setStorageSync("address", res3);
        //console.log(res3);
      }
    } catch (error) {
      console.log(error);
    }
    
  },
  getCartList(){
    const cartList=wx.getStorageSync("cart");
    this.setData({
      cartList
    })
    console.log(cartList);
     
  },
  handleChk(e){
    const {id} = e.currentTarget.dataset;
    const cartList = wx.getStorageSync("cart")
    //const index = cartList.find(id)
    cartList.forEach(r=>{
      if (r.goods_id===id) {
        r.checked = r.checked?false:true
      }
    })
    wx.setStorageSync("cart", cartList);
    this.loadCart()
  },
  handleAllChk(){
    let totalCost = this.data.totalCost
    let totalNum = this.data.totalNum
    const cartList = wx.getStorageSync("cart")
    if (this.data.allChecked) {
      let allChecked=false
      cartList.forEach(r=>r.checked=false)
      totalCost = 0
      totalNum = 0
      this.setData({
        allChecked,
        cartList,
        totalCost,
        totalNum
      })
    }else{
      cartList.forEach(r => r.checked = true)
      this.loadCart(cartList)
    }
    wx.setStorageSync("cart", cartList);
  },
  handleMin(e) {
    const {index} = e.currentTarget.dataset;
    const cartList = wx.getStorageSync("cart")
    
    if (cartList[index].num === 1) {
      wx.showModal({
        title: '提示',
        content: '是否要删除？',
        showCancel: true,
        cancelText: '取消',
        cancelColor: '#000000',
        confirmText: '确定',
        confirmColor: '#3CC51F',
        success: (result) => {
          if (result.confirm) {
            cartList.splice(index,1)
            wx.setStorageSync("cart", cartList);
            this.loadCart()
          }
        },
        fail: () => {},
        complete: () => {}
      });
    }else{
      cartList[index].num = cartList[index].num > 1 ? cartList[index].num - 1 : cartList[index].num
      cartList[index].checked = cartList[index].num === 0 ? false : cartList[index].checked
      wx.setStorageSync("cart", cartList);
      this.loadCart()
    }
  },
  handleAdd(e) {
    const {index} = e.currentTarget.dataset;
    const cartList = wx.getStorageSync("cart")
    if (cartList[index].num >= 0) {
      cartList[index].num = cartList[index].num+1
    }
    wx.setStorageSync("cart", cartList);
    this.loadCart()
  },
  async handlePay(){
    const {address,totalNum} = this.data
    if (!address.userName) {
      await showToast({title:'没有收货地址'})
      return
    }
    if (totalNum===0) {
      await showToast({title:'没有商品'})
      return
    }
    //跳转支付页面
    wx.navigateTo({
      url:'/pages/pay/index'
    })
  },
  loadCart(cart) {
    let cartList = wx.getStorageSync("cart") || [];
    cartList = cart ? cart : cartList
    //计算全选
    //const allChecked=cartList.length?cartList.every(v=>v.checked):false
    let allChecked = true
    let totalCost = 0
    let totalNum = 0
    cartList.forEach((r) => {
      if (r.checked) {
        totalCost += r.goods_price * r.num
        totalNum += r.num
      } else {
        allChecked = false
      }
    })
    //数组为空时 false
    if (cartList.length === 0) {
      allChecked = false
    }
    //allChecked=(cartList.length!=0)?allChecked:false
    this.setData({
      cartList,
      allChecked,
      totalCost,
      totalNum
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //this.getCartList()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const address = wx.getStorageSync("address");
    this.setData({
      address
    })
    this.loadCart()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})